package com.alibaba.org.service.impl;

import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.org.domain.Department;
import com.alibaba.org.domain.Systemdictionarydetail;
import com.alibaba.org.mapper.DepartmentMapper;
import com.alibaba.org.mapper.EmployeeMapper;
import com.alibaba.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
      @Autowired
      private DepartmentMapper departmentMapper;

      @Autowired
      private EmployeeMapper employeeMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Systemdictionarydetail> detailById(Long id) {
        return departmentMapper.detailById(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        departmentMapper.delete(id);
        employeeMapper.deleteByDeptId(id);
    }

    /**
     * 高级技师玩法 这种玩法你们必须掌握
     */
    @Override
    public List<Department> tree() {
        List<Department> result = new ArrayList<>();
        // 查询所有数据
        List<Department> allDepts = findAll();
        // 将allDepts 转成map   key：id    value：dept对象
        Map<Long, Department> deptMap = allDepts.stream().collect(Collectors.toMap(Department::getId, dept->dept));
        // 遍历集合
        for (Department dept : allDepts) {
            if (null == dept.getParentId()){
                // 顶级部门
                result.add(dept);
            }else {
                Department parent = deptMap.get(dept.getParentId());
                if (null != parent){
                    parent.getChildren().add(dept);
                }

            }
        }
        return result;
    }
}
